package com.ycl.filter;

import com.alibaba.fastjson.JSON;
import com.ycl.common.BaseThread;
import com.ycl.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@WebFilter(filterName = "loginCheckFilter",urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    // 路径比较工具
    private static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        // 获取请求的URL
        String requestURL = request.getRequestURI();

        log.info("拦截到请求：{}",requestURL);

        // 定义不需要处理的请求路径
        String[] urls = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/user/sendMsg",
                "/user/login",
        };

        // 判断本次请求是否需要处理
        boolean check = check(urls, requestURL);

        // 如果不需要处理，则直接放行
        if (check){
            log.info("无需处理的请求：{}",requestURL);
            filterChain.doFilter(request,response);
            return;
        }
        // 需要处理，判断登录，如已登陆，则放行 employee
        if (request.getSession().getAttribute("employee")!= null){
            log.info("用户已登陆：{}",request.getSession().getAttribute("employee"));

            // 将用户ID存入ThreadLocal
            Long empId = (Long) request.getSession().getAttribute("employee");
            BaseThread.setCurrentId(empId);

            filterChain.doFilter(request,response);
            return;
        }
        // 需要处理，判断登录，如已登陆，则放行 employee user
        if (request.getSession().getAttribute("user")!= null){
            log.info("用户已登陆：{}",request.getSession().getAttribute("user"));

            // 将用户ID存入ThreadLocal
            Long userId = (Long) request.getSession().getAttribute("user");
            BaseThread.setCurrentId(userId);

            filterChain.doFilter(request,response);
            return;
        }
        // 如果没有登录则返回未登录结果，通过输出流方式向客户端页面响应数据
        log.info("用户为登录");
        response.getWriter().write(JSON.toJSONString(Result.error("NOTLOGIN")));
    }
    public boolean check(String[] urls,String requestURI ){
        for (String url : urls) {
            boolean check = PATH_MATCHER.match(url, requestURI);
            if (check)
                return true;
        }
        return false;
    }
}
